<template>
  <div>

    <div class="header-select">
      <el-cascader clearable ref="cascaderData" class="select" :show-all-levels="true" v-model="folderId"
        :options="folders" :props="{checkStrictly: true }"></el-cascader>
      <el-button class="btn" type="danger" round @click="batchDelete()">批量删除
        <i class="el-icon-delete el-icon--right"></i>
      </el-button>

      <el-button class="btn" type="primary" round @click="toCreateShare()">创建共享文件夹
        <i class="el-icon-share el-icon--right"></i>
      </el-button>
    </div>


    <!-- 表格 -->
    <div class="table">
      <el-table ref="shareData" :data="shareData" style="width: auto">
        <el-table-column type="selection" />
        <el-table-column prop="" label="" width="40px">
          <i class="el-icon-share"></i>
        </el-table-column>
        <el-table-column prop="id" label="共享ID" width="200px"></el-table-column>
        <el-table-column prop="folderName" label="文件名" width="auto"></el-table-column>
        <el-table-column label="开始时间" width="200px">
          <template slot-scope="scope">
            <i class="el-icon-time" v-if="scope.row.startDate"></i>
            <span style="margin-left: 10px">{{ formatDate(scope.row.startDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="200px">
          <template slot-scope="scope">
            <i class="el-icon-time" v-if="scope.row.deadlineDate"></i>
            <span style="margin-left: 10px">{{ formatDate(scope.row.deadlineDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="foreverStr" label="是否永久" width="auto"></el-table-column>
        <el-table-column prop="password" label="提取密码" width="auto"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="update(scope.row)" type="text" size="small">修改</el-button>
            <el-button type="text" size="small" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="pageSizes" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 修改弹窗 -->
    <!-- <el-dialog title="文件修改" class="update_dialog" :visible.sync="dialog">

    </el-dialog> -->

    <el-drawer title="修改共享文件夹" :visible.sync="dialog" direction="rtl">
      <el-form status-icon label-width="100px" class="demo-ruleForm">
        <!-- 下拉框 -->
        <el-form-item v-if="!forever" label="共享日期：">
          <el-date-picker v-model="date" type="daterange" align="right" unlink-panels range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="是否永久：">
          <el-switch v-model="forever" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
        <!-- 文件名 -->
        <el-form-item label="提取密码：">
          <el-input v-model="password" placeholder="请输文件提取密码" style="width: 300px;"></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submit()">提交</el-button>
          <el-button @click="cencel()">取消</el-button>
        </el-form-item>

      </el-form>
    </el-drawer>

  </div>
</template>

<script>
  import apiUrl from '@/api/url'
  import link from '@/api/Link'
  import router from "@/router"
  import sizeTostr from '@/util/FileSizeUtil'
  import * as dateUtils from "@/util/DateUtil";

  export default {
    name: 'ShareFolder',
    components: {

    },
    data () {
      return {
        pageSize: 5,
        pageSizes: [10, 15, 20, 30],
        currentPage: 1,
        total: 0,
        shareData: [],
        folders: [],
        folderId: [],
        dialog: false,

        date: [],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick (picker) {
              const start = new Date();
              const end = new Date();
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        forever: false,
        password: '',
        shareId: '',

        delId: [],
      }
    },
    methods: {
      //初始化
      init () {

        let data = {
          folderId: this.folderId[this.folderId.length - 1],
          page: {
            pageSize: this.pageSize,
            pageNo: this.currentPage,
          },
        }
        link(apiUrl.baseUrl + '/sys/share/findByPage/v1', 'POST', JSON.stringify(data), null).then((ok) => {
          if (ok.data.code === 0) {
            this.total = ok.data.data.total
            this.shareData = ok.data.data.shares
            this.shareData.forEach(share => {
              share.foreverStr = share.forever == 0 ? '否' : '是'
            })
          } else {
            this.$message.error('数据请求失败：' + ok.data.msg)
          }
        })

      },
      //构建下拉框
      cascaderInit (data) {
        if (!data) {
          return
        }
        let folders = {
          value: data.folder.id,
          label: data.folder.folderName,
          children: []
        }

        data.childFolders.forEach(element => {
          folders.children.push(this.cascaderInit(element))
        });

        return folders;
      },
      //分页监控
      handleCurrentChange (val) {
        this.currentPage = val
        this.init()
      },
      //分页监控
      handleSizeChange (val) {
        this.pageSize = val;
        this.init()
      },
      //修改
      update (row) {
        if (row.forever == 0) {
          this.date = []
          this.date.push(row.startDate)
          this.date.push(row.deadlineDate)
        }
        this.password = row.password
        this.forever = row.forever == 0 ? false : true
        this.shareId = row.id
        this.dialog = true
      },

      cencel () {
        this.dialog = false;
      },
      //执行修改
      submit () {

        let data = {
          id: this.shareId,
          password: this.password,
          forever: this.forever ? 1 : 0,
        }
        if (!this.forever) {
          data.startDate = this.date[0]
          data.deadlineDate = this.date[1]
        }
        link(apiUrl.baseUrl + '/sys/share/updateShare/v1', 'POST', JSON.stringify(data)).then(ok => {
          if (ok.data.code == 0) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.init()
            this.dialog = false;
          } else {
            this.$message({
              message: ok.data.msg,
              type: "error",
            });
          }
        })
      },
      //删除
      del (row) {
        this.delId = []
        this.delId.push(row.id)
        this.remove()
      },
      //批量删除
      batchDelete () {
        this.delId = []
        let selection = this.$refs.shareData.selection;

        for (let index = 0; index < selection.length; index++) {
          const element = selection[index];
          this.delId.push(element.id)
        }
        if (this.delId.length == 0) {
          this.$message({
            message: "请选择文件",
            type: "warning",
          });
          return
        }
        this.remove()
      },
      //执行删除
      remove () {
        this.$confirm('此操作将取消文件夹共享, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            ids: this.delId
          }
          link(apiUrl.baseUrl + '/sys/share/deleteShare/v1', 'POST', JSON.stringify(data)).then(ok => {
            if (ok.data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.init()
            } else {
              this.$message({
                message: ok.data.msg,
                type: "error",
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //跳转创建共享文件夹页面
      toCreateShare () {
        this.$router.push('/create?type=share')
      },
      //时间格式化
      formatDate (dateStr) {
        let date = new Date(dateStr);
        return dateUtils.formatDate(date, 'yyyy/MM/dd');
      },
    },
    mounted () {
      let user = JSON.parse(localStorage.getItem('user'))
      let cascader = {
        state: 0,
        id: user.rootId
      }
      //下拉框--获取数据
      link(apiUrl.baseUrl + '/sys/folder/findList/v2', 'POST', JSON.stringify(cascader), null).then((ok) => {
        if (ok.data.code == 0) {
          this.folders.push(this.cascaderInit(ok.data.data))
          this.init()
        } else {
          this.$message({
            message: ok.data.msg,
            type: "error",
          });
        }
      })
    },
    watch: {
      folderId (curVal, oldVal) {
        this.init()
      },
    }

  }
</script>

<style scoped>
  .table {
    margin: 10px;
    /* width: 90%;   */
  }

  .header-select {
    margin: 10px;
  }

  .btn {
    margin-left: 10px;
  }
</style>